<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- options指定数据源 props指定配置对象 -->
      <p class="cat_opt">
        选择商品分类：
        <el-cascader
          expand-trigger="hover"
          :options="parentCateList"
          :props="parentCateProps"
          v-model="seletedKeys"
          @change="parentCateChanged"
        >
        </el-cascader>
      </p>
      <el-tabs v-model="activeName" type="card" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="add_dialogVisible = true"
            >添加参数</el-button
          >
          <!-- 参数列表区域 -->
          <el-table :data="paramsDataByMany" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="tagClose(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <!-- 输入框和按钮切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="InputConfirm(scope.row)"
                  @blur="InputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getParamsById(scope.row.attr_id)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParamsById(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="add_dialogVisible = true"
            >添加属性</el-button
          >
          <!-- 参数列表区域 -->
          <el-table :data="paramsDataByOnly" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="tagClose(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <!-- 输入框和按钮切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="InputConfirm(scope.row)"
                  @blur="InputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getParamsById(scope.row.attr_id)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParamsById(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="add_dialogVisible"
      width="30%"
      @close="addParamsClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="90px"
      >
        <el-form-item :label="titleText + ':'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="add_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="update_dialogVisible"
      width="30%"
      @close="updateParamsClosed"
    >
      <el-form
        :model="updateParamsForm"
        :rules="updateParamsRules"
        ref="updateParamsRef"
        label-width="90px"
      >
        <el-form-item :label="titleText + ':'" prop="attr_name">
          <el-input v-model="updateParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="update_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //  父级分类列表
      parentCateList: [],
      // 级联选择器的配置属性
      parentCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },

      //  选中父级的id
      seletedKeys: [],
      activeName: 'many',
      paramsDataByMany: [],
      paramsDataByOnly: [],
      // 添加对话框的显示与隐藏
      add_dialogVisible: false,
      // 编辑对话框的显示与隐藏
      update_dialogVisible: false,
      addParamsForm: {
        attr_name: '',
      },
      addParamsRules: {
        attr_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      updateParamsForm: {},
      updateParamsRules: {
        attr_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getParentCateList()
  },
  methods: {
    // 获取商品分类数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取父级分类失败')
      this.parentCateList = res.data
    },
    // 监听添加对话框的关闭
    addParamsClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 监听添加对话框的关闭
    updateParamsClosed() {
      this.$refs.updateParamsRef.resetFields()
    },
    // 提交添加的属性/参数
    addParams() {
      this.$refs.addParamsRef.validate(async (data) => {
        if (!data) return
        const { data: res } = await this.$http.post(
          `categories/${this.paramsId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.add_dialogVisible = false
        this.getParamsData()
      })
    },
    // 获取商品属性/参数
    async getParamsById(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.paramsId}/attributes/${id}`,
        {
          attr_sel: this.activeName,
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.updateParamsForm = res.data
      this.update_dialogVisible = true
    },
    // 提交编辑的属性/参数
    updateParams() {
      this.$refs.updateParamsRef.validate(async (data) => {
        if (!data) return
        const { data: res } = await this.$http.put(
          `categories/${this.paramsId}/attributes/${this.updateParamsForm.attr_id}`,
          {
            attr_name: this.updateParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        this.update_dialogVisible = false
        this.getParamsData()
      })
    },
    async deleteParamsById(id) {
      // 弹框询问是否删除数据
      const result = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //   console.log(result);
      // console.log(id);
      if (result !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.paramsId}/attributes/${id}`
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 商品父级分类的改变
    parentCateChanged() {
      this.getParamsData()
    },
    // 根据所选商品分类显示对应数据
    async getParamsData() {
      if (this.seletedKeys.length !== 3) {
        this.seletedKeys = []
        this.paramsDataByMany =[]
        this.paramsDataByOnly = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.paramsId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )

      if (res.meta.status !== 200)
        return this.$message.error('获取参数列表失败')
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制按钮与文本框的切换显示
        item.inputVisible = false
        // 输入框内容
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.paramsDataByMany = res.data
      } else {
        this.paramsDataByOnly = res.data
      }
    },
    tabClick() {
      this.getParamsData()
    },
    // 失去焦点或enter都会触发
    InputConfirm(row) {
      let inputValue = row.inputValue
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return,则说明有内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求保存至数据库
      this.saveAttrVals(row)
    },
    // 参数可选项发起请求保存至数据库
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.paramsId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('修改参数项成功')
      this.getParamsData()
    },
    // 点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true
      // 获取焦点 $nextTick作用:当页面上元素被重新渲染后,才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数可选项
    tagClose(i, row) {
      row.attr_vals.splice(i ,1)
      this.saveAttrVals(row)
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.seletedKeys.length !== 3) {
        return true
      }
      return false
    },
    paramsId() {
      if (this.seletedKeys.length === 3) {
        return this.seletedKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 150px;
  margin-left: 10px;
  // vertical-align: bottom;
}
</style>